import {
  getConversationsApi, getPreviousMessagesApi, toggleTypingStatusApi, messageApi
} from '../../../api/conversation'
import { createPendingMessage } from '../../../helpers/commons'
import { MESSAGE_STATUS, MESSAGE_TYPE } from '../../../constants/messages'
export const actions = {
  getConversations: async ({ commit }, {
    inboxId,
    status,
    assigneeType,
    page
  }) => {
    const { data } = await getConversationsApi({
      inboxId,
      status,
      assigneeType,
      page
    })

    const conversations = data.data.payload

    commit('clearConversations')
    commit('updateConversations', conversations)
  },

  fetchPreviousMessages: async ({ commit }, data) => {
    const {
      data: { payload }
    } = await getPreviousMessagesApi(data)

    commit('setPreviousConversations', {
      id: data.conversationId,
      data: payload
    })
  },

  async setActiveChat ({ dispatch }, data) {
    await dispatch('fetchPreviousMessages', {
      conversationId: data.id,
      before: data.messages[0].createdAt
    })
  },

  toggleTypingStatus (_, data) {
    toggleTypingStatusApi(data)
  },

  updateCurrentConversationId: ({ commit }, data) => {
    commit('setCurrentConversationId', {
      id: data
    })
  },

  createPendingMessageAndSend: ({ dispatch }, data) => {
    const pendingMessage = createPendingMessage(data)
    dispatch('sendMessageWithData', pendingMessage)
  },

  sendMessageWithData: async ({ commit }, pendingMessage) => {
    commit('ADD_MESSAGE', {
      ...pendingMessage,
      status: MESSAGE_STATUS.PROGRESS
    })
    const response = await messageApi(pendingMessage)
    commit('ADD_MESSAGE', {
      ...response.data,
      status: MESSAGE_STATUS.SENT
    })
  },

  addMessage ({ commit }, message) {
    commit('ADD_MESSAGE', message)
    if (message.message_type === MESSAGE_TYPE.INCOMING) {
    }
  },

  addConversation ({ commit }, conversation) {
    commit('ADD_CONVERSATION', conversation)
  }
}
